package com.example.demo.service.impl;

import com.example.demo.model.*;
import com.example.demo.model.vo.PlantAddVo;
import com.example.demo.model.vo.PlantCerteriaVo;
import com.example.demo.model.vo.PlantUpdateVo;
import com.example.demo.model.vo.PlantVo;
import com.example.demo.repository.LegalPersonReposirtory;
import com.example.demo.repository.PlantReposirtory;
import com.example.demo.service.PlantService;
import com.example.demo.util.AllRecords;
import com.example.demo.util.Result;
import com.example.demo.util.ResultVO;
import com.querydsl.core.types.dsl.Expressions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by Lx on 2018/6/27.
 */
@Service

public class PlantServiceImpl implements PlantService {

    /**
     *
     */
    @Autowired
    private PlantReposirtory plantReposirtory;
    @Autowired
    private LegalPersonReposirtory legalPersonReposirtory;
    //通过此方法拿到注解策略中的自增ID
    private final static AtomicInteger idGenerator = new AtomicInteger();

    public Result<AllRecords<PlantVo>> queryPage(PlantCerteriaVo query) {
        com.querydsl.core.types.dsl.BooleanExpression booleanExpression = Expressions.asBoolean(true).isTrue();

        if(!StringUtils.isEmpty(query.getLegalPersonId())){
            booleanExpression = booleanExpression.and(QPlant.plant.legalPersonId.eq(query.getLegalPersonId()));
        }
        if(!StringUtils.isEmpty(query.getCode())){
            booleanExpression = booleanExpression.and(QPlant.plant.code.eq(query.getCode()));
        }
        if(query.getStatus()!=null&&query.getStatus()!= StatusEnum.QUANBU.getStatus()){
                booleanExpression = booleanExpression.and(QPlant.plant.status.eq(query.getStatus()));
        }
        // 查找到数据
        Page<Plant> result =  plantReposirtory.findAll(booleanExpression,
                new PageRequest(query.getPageIndex()-1,query.getPageSize(),new Sort(Sort.Direction.DESC,"createTime")));
        //给确实的名称或字段赋值
        List<Plant> plantList = assignment(result.getContent());
        AllRecords<Plant> allRecords = new AllRecords();
        allRecords.setDataList(plantList);
        allRecords.setPageIndex(query.getPageIndex());
        allRecords.setPageSize(query.getPageSize());
        allRecords.setTotalNumber(result.getTotalElements());
        allRecords.setTotalPage(result.getTotalPages());
        return ResultVO.success(allRecords);
    }

    public List<Plant> assignment(List<Plant> plantList){
        //声明一个List用来存放法人Id信息
        List<Integer> legalPersonIdList = new ArrayList();
        //给启用禁用赋值
        for (Plant plant : plantList){
            if (plant.getStatus().equals(StatusEnum.QIYONG.getStatus())){
                plant.setStatusName(StatusNameEnum.QIYONG.getStatus());
            }
            if (plant.getStatus().equals(StatusEnum.JINYONG.getStatus())){
                plant.setStatusName(StatusNameEnum.JINYONG.getStatus());
            }
            legalPersonIdList.add(plant.getLegalPersonId());
        }
        //排重
        legalPersonIdList = new ArrayList(new HashSet(legalPersonIdList));
        //给法人编码法人名称赋值
        List<LegalPerson> legalPersonList = legalPersonReposirtory.findByIdIn(legalPersonIdList);
        for  (Plant plant : plantList){
            for (LegalPerson legalPerson:legalPersonList){
                if (plant.getLegalPersonId()==legalPerson.getId()){
                    plant.setLegalPersonName(legalPerson.getName());
                    plant.setLegalPersonCode(legalPerson.getCode());
                }
            }
        }
        return plantList;
    }

    public Result<PlantUpdateVo> updatePlant(PlantUpdateVo plantUpdateVo) {
        //验证ID是否存在
        Plant plant = plantReposirtory.findOne(plantUpdateVo.getId());
        if (plant==null){
            return ResultVO.error(500,"修改对象不存在！");
        }
        BeanUtils.copyProperties(plantUpdateVo,plant);
        plantReposirtory.save(plant);
        return ResultVO.success(plant);
    }

    public Result<PlantAddVo> addPlant(PlantAddVo plantAddVo) {
        //验证数据是否合法
        Result<PlantAddVo> plantAddVoResult = validData(plantAddVo);
        if (!plantAddVoResult.getStatus()){
            return ResultVO.error(plantAddVoResult.getCode(),plantAddVoResult.getMsg());
        }
        Plant plant = new Plant();
        BeanUtils.copyProperties(plantAddVo,plant);
        Integer id = idGenerator.incrementAndGet();
        plant.setId(id);
        plantReposirtory.save(plant);
        return ResultVO.success(plant);
    }

    private Result<PlantAddVo> validData(PlantAddVo plantAddVo){
        //验证工厂编码是否唯一，传入工厂编码到数据库中查询是否存在工厂编码
        List<Plant> plantList = plantReposirtory.findByCode(plantAddVo.getCode());
        if (!CollectionUtils.isEmpty(plantList)){
            return ResultVO.error(500,"工厂编码已存在！");
        }
        //验证法人编码是否存在
        LegalPerson legalPerson = legalPersonReposirtory.findOne(plantAddVo.getLegalPersonId());
        if (legalPerson==null){
            return ResultVO.error(500,"法人信息不存在！");
        }
        return ResultVO.success(plantAddVo);
    }
}
